/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package seso;

import java.io.*;
import javax.swing.JOptionPane;
import jxl.*;
import jxl.write.*;

/**
 *
 * @author Administrator
 */
public class ExcelFileTools {

    public static boolean createExcelFile(String fileName, String sheetName, int sheetIndex) {
        boolean result = true;
        WritableWorkbook wwb = null;
        try {
            //首先要使用Workbook类的工厂方法创建一个可写入的工作薄(Workbook)对象
            wwb = Workbook.createWorkbook(new File(fileName));
        } catch (Exception exp) {
            result = false;
            JOptionPane.showMessageDialog(null, "Exception : " + exp.getMessage(), "", JOptionPane.ERROR_MESSAGE);
        }
        if (wwb != null) {
            //创建一个可写入的工作表
            //Workbook的createSheet方法有两个参数，第一个是工作表的名称，第二个是工作表在工作薄中的位置
            wwb.createSheet(sheetName, sheetIndex);


            try {
                //从内存中写入文件中
                wwb.write();
                //关闭资源，释放内存
                wwb.close();
            } catch (Exception exp) {
                result = false;
                JOptionPane.showMessageDialog(null, "Exception : " + exp.getMessage(), "", JOptionPane.ERROR_MESSAGE);
            }
        }

        return result;
    }
    
    public static boolean removeExcelSheet(String fileName, int sheetIndex) {
        boolean result = true;
        Workbook wb = null;
        WritableWorkbook wwb = null;
        try {
            wb = Workbook.getWorkbook(new File(fileName));
            wwb = Workbook.createWorkbook(new File(fileName), wb);
        } catch (Exception exp) {
            result = false;
            JOptionPane.showMessageDialog(null, "Exception : " + exp.getMessage(), "", JOptionPane.ERROR_MESSAGE);
        }
        if (wwb != null) {
            wwb.removeSheet(sheetIndex);
            try {
                wwb.write();
                wwb.close();
            } catch (Exception exp) {
                result = false;
                JOptionPane.showMessageDialog(null, "Exception : " + exp.getMessage(), "", JOptionPane.ERROR_MESSAGE);
            }
        }

        return result;
    }    

}
